import { mockEnabled } from "@/api/mock";

function readToken() {
  const tokenInfo = localStorage.getItem("token");
  if (tokenInfo === null) {
    return null;
  }

  let token;
  try {
    token = JSON.parse(tokenInfo);
  } catch (ex) {
    return null;
  }

  if (token == null || typeof token != "object" || typeof token.token != "string" || typeof token.expireTime != "number") {
    return null;
  }

  if (mockEnabled.value != true) {
    const now = (Date.now() / 1000) | 0;
    if (now >= token.expireTime) {
      return null;
    }
  }

  return token.token;
}

function requireToken() {
  const token = readToken();
  if (token === null) {
    throw Error("没有登录或登录失效");
  }

  return token;
}

function installToken(token, expireTime) {
  localStorage.setItem("token", JSON.stringify({
    token,
    expireTime
  }));
}

function clearToken() {
  localStorage.removeItem("token");
}

export {
  readToken,
  requireToken,
  installToken,
  clearToken
};
